package com.zjs.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的url
        String requestURI = request.getRequestURI();

        // 检查是否是静态资源请求，例如CSS、JS等，这里以.css和.js作为示例
        if (requestURI.endsWith(".css") || requestURI.endsWith(".js") ||
                requestURI.endsWith(".jpg") || requestURI.endsWith(".png") ||
                requestURI.endsWith(".gif")) {
            // 直接放行静态资源请求
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //如果是登录页面，则通过
        if (requestURI.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else {
            if (request.getSession().getAttribute("user") != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                response.sendRedirect("/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {
    }
}
